import datetime
import time

from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.shortcuts import render

from anysis.models import bucket, bk_classroom
from index.models import VStuShow, UserInfo, YJS, JZG, JwToRenshi
from index.utils import Department
from index.views import UserModel
from .models import bks


# Create your views here.

def get_form1(request):
    context = dict()
    username = request.session.get("user", None)
    if username is None:
        return HttpResponseRedirect("../index")
    return render(request, "form1.html", context)


def get_form2(request):
    context = dict()
    username = request.session.get("user", None)
    if username is None:
        return HttpResponseRedirect("../index")
    usertype = request.session.get("user_type")
    if request.method == "POST":
        now = datetime.datetime.now().strftime("%Y-%m-%d")
        if usertype == 0:
            user = VStuShow.objects.db_manager("jw").get(username=username)
            try:
                o = bks.objects.get(createdate__contains=now, userid=username, usertype=usertype, depid=user.class_id)
            except ObjectDoesNotExist:
                o = bks.objects.create(userid=username, createdate=now, usertype=usertype, depid=user.class_id)
        elif usertype == 1:
            user = YJS.objects.get(userid=username)
            try:
                o = bks.objects.get(createdate__contains=now, userid=username, usertype=usertype,
                                    depid=Department(user.depid).getroot().idn)
            except ObjectDoesNotExist:
                o = bks.objects.create(userid=username, createdate=now, usertype=usertype,
                                       depid=Department(user.depid).getroot().idn)
        elif usertype == 2:
            user = JZG.objects.get(userid=username)
            try:
                o = bks.objects.get(createdate__contains=now, userid=username, usertype=usertype,
                                    depid=Department(user.depid).getroot().idn)
            except ObjectDoesNotExist:
                o = bks.objects.create(userid=username, createdate=now, usertype=usertype,
                                       depid=Department(user.depid).getroot().idn)
        return render(request, "form2.html", context)
    else:
        return HttpResponseRedirect("../index")


def get_form3(request):
    username = request.session.get("user", None)
    usertype = request.session.get("user_type")
    context = dict()
    if request.method == "POST":
        now = datetime.datetime.now().strftime("%Y-%m-%d")
        o = bks.objects.get(userid=username, createdate__contains=now)
        isinschool = request.POST.get("isinschool", "0")
        location = request.POST.getlist("location")
        if isinschool is "0":
            o.isinschool = True
            o.location = location[0]
        else:
            o.isinschool = False
            o.location = location[1]
        print(o.location)
        ispassed = int(request.POST.get("ispassed", None))
        if ispassed is not None:
            o.ispassed = int(ispassed)
        if ispassed is not 0:
            planedtravel_time = request.POST.get("planedtravel_time", None)
            if planedtravel_time is not None:
                planedtravel_time = datetime.datetime.strptime(planedtravel_time, '%Y-%m-%d')
                o.planedtravel_time = planedtravel_time
            planedleave_time = request.POST.get("planedleave_time", None)
            if planedleave_time is not None:
                planedleave_time = datetime.datetime.strptime(planedleave_time, '%Y-%m-%d')
                o.planedleave_time = planedleave_time
        is_go_to_outer = request.POST.get("is_go_to_outer", "0")
        if is_go_to_outer is "0":
            o.is_go_to_outer = False
        else:
            o.is_go_to_outer = True
        isplanedtravel = request.POST.get("isplanedtravel", "0")
        if isplanedtravel is "0":
            o.isplanedtravel = False
        else:
            o.isplanedtravel = True
            plan_back_time = request.POST.get("plan_back_time", None)
            if plan_back_time is not None:
                plan_back_time = datetime.datetime.strptime(plan_back_time, '%Y-%m-%d')
                o.plan_back_time = plan_back_time
            trans_type = request.POST.get("trans_type", None)
            if trans_type is not None:
                o.trans_type = int(trans_type)
        o.save()
        return render(request, "form3.html", context)
    else:
        return HttpResponseRedirect("../index/")


def get_complete(request):
    username = request.session.get("user", None)
    usertype = request.session.get("user_type")
    context = dict()
    if request.method == "POST":
        now = datetime.datetime.now().strftime("%Y-%m-%d")
        o = bks.objects.get(userid=username, createdate__contains=now)
        isfever = request.POST.get("isfever", "0")
        if isfever is "0":
            o.isfever = False
            isseen = int(request.POST.get("isseen", "0"))
            o.isseen = isseen
            hospital = request.POST.get("hospital", None)
            if hospital is not None:
                o.hospital = hospital
            isisolated = int(request.POST.get("isisolated", 2))
            if isisolated is not None:
                o.isisolated = isisolated
        else:
            o.isfever = True
        is_atach_patient = request.POST.get("is_atach_ patient", "0")
        if is_atach_patient is "0":
            o.is_atach_patient = False
        else:
            o.is_atach_patient = True
        folk_attach = request.POST.get("folk_attach", "0")
        if folk_attach is "0":
            o.folk_attach = False
        else:
            o.folk_attach = True
        o.save()
        if usertype == 0:
            user = VStuShow.objects.db_manager("jw").get(username=username)
            jwbm = bk_classroom.objects.get(classid=user.class_id).depid
            depid = JwToRenshi.objects.get(jwbm=jwbm).renshi_bm
            try:
                b_usr = bucket.objects.get(createdate__contains=now, depid=depid)
            except ObjectDoesNotExist:
                b_usr = bucket.objects.create(createdate=now, usertype=0, depid=depid)
        elif usertype == 1:
            user = YJS.objects.get(userid=username)
            try:
                b_usr = bucket.objects.get(createdate__contains=now, depid=Department(user.depid).getroot().idn)
            except ObjectDoesNotExist:
                b_usr = bucket.objects.create(createdate=now, usertype=usertype,
                                              depid=Department(user.depid).getroot().idn)
        elif usertype == 2:
            user = JZG.objects.get(userid=username)
            try:
                b_usr = bucket.objects.get(createdate__contains=now, depid=Department(user.depid).getroot().idn)
            except ObjectDoesNotExist:
                b_usr = bucket.objects.create(createdate=now, usertype=usertype,
                                              depid=Department(user.depid).getroot().idn)
        is_faver = list(eval(b_usr.is_faver))
        submited = list(eval(b_usr.submited))
        is_passed = list(eval(b_usr.is_passed))
        is_deacted = list(eval(b_usr.is_deacted))
        isinschool = list(eval(b_usr.isinschool))
        is_go_to_outer = list(eval(b_usr.is_go_to_outer))
        isplanedtravel = list(eval(b_usr.isplanedtravel))
        folk_attach = list(eval(b_usr.folk_attach))
        is_unsearch = list(eval(b_usr.is_unsearch))
        is_atach_patient = list(eval(b_usr.is_atach_patient))
        if o.isinschool is True:
            isinschool.append(username)
        else:
            try:
                isinschool.remove(username)
            except:
                pass
        if o.isplanedtravel is True:
            isplanedtravel.append(username)
        else:
            try:
                isplanedtravel.remove(username)
            except:
                pass
        if o.is_atach_patient is True:
            is_atach_patient.append(username)
        else:
            try:
                is_atach_patient.remove(username)
            except:
                pass
        if o.folk_attach is True:
            folk_attach.append(username)
        else:
            try:
                folk_attach.remove(username)
            except:
                pass
        if o.isseen is 0:
            is_unsearch.append(username)
        else:
            try:
                is_unsearch.remove(username)
            except:
                pass
        if o.is_go_to_outer is True:
            is_go_to_outer.append(username)
        else:
            try:
                is_go_to_outer.remove(username)
            except:
                pass
        if o.isfever is True:
            is_faver.append(username)
        else:
            try:
                is_faver.remove(username)
            except:
                pass
        if o.ispassed is not 0:
            is_passed.append(username)
        else:
            try:
                is_passed.remove(username)
            except:
                pass
        if o.isseen is 2:
            is_deacted.append(username)
        else:
            try:
                is_deacted.remove(username)
            except:
                pass
        if username not in submited:
            submited.append(username)
        b_usr.submited = submited
        b_usr.is_deacted = is_deacted
        b_usr.is_passed = is_passed
        b_usr.is_faver = is_faver
        b_usr.save()
        resultsets = bks.objects.filter(userid=username)
        timelist = list()
        for index, result in enumerate(resultsets):
            timelist.append(timelistitem(index, int(time.mktime(result.createdate.timetuple()))))
        context["timelist"] = timelist
        return render(request, "form_compulete.html", context)
    else:
        return HttpResponseRedirect("../index/")


def complete(request):
    username = request.session.get("user")
    usertype = request.session.get("user_type")
    context = dict()
    if request.method == "POST":
        # TODO:PhoneNumber,residence,isplanedtravel,isinschool
        if usertype == 0:
            user = VStuShow.objects.db_manager("jw").get(username=username)
            usr_show = UserModel(username=username, usertype=usertype)
            usr_show.realname = user.realname
            usr_show.gander = user.gendar
            usr_show.department = user.department
            usr_show.batch = user.class_field

        elif usertype == 1:
            user = YJS.objects.get(userid=username)
            usr_show = UserModel(username=username, usertype=usertype)
            usr_show.realname = user.realname
            usr_show.gander = user.get_gander_display()
            usr_show.department = Department(user.depid).getroot().name
            usr_show.batch = usr_show.department
        elif usertype == 2:
            user = JZG.objects.get(userid=username)
            usr_show = UserModel(username=username, usertype=usertype)
            usr_show.realname = user.realname
            usr_show.gander = user.get_gander_display()
            try:
                usr_show.department = Department(user.depid).getroot().name
            except ObjectDoesNotExist:
                usr_show.department = "Unknown"
            usr_show.batch = "教职工"
        phonenumber = request.POST.get("phonenumber", None)
        residence = request.POST.get("residence", None)

        try:
            userinfo = UserInfo.objects.get(userid=username, usertype=usertype)
            userinfo.phonenumber = phonenumber
            userinfo.residence = residence
            userinfo.save()
        except ObjectDoesNotExist:
            userinfo = UserInfo.objects.create(userid=username, phonenumber=phonenumber, residence=residence,
                                               usertype=usertype)
        context["user"] = usr_show
        context["userinfo"] = userinfo
        context["Complete"] = True
        context["user_type"] = usertype
        return render(request, "confirm.html", context)
    else:
        return HttpResponseRedirect("../index")


class timelistitem:
    def __init__(self, index, value):
        self.index = index
        self.value = value
